//
//  LCInfoWebVC.m
//  TheLCNews
//
//  Created by apple on 15/11/30.
//  Copyright © 2015年 LC. All rights reserved.
//

#import "LCInfoWebVC.h"
#import "LCInfoCoCell.h"
#import "LCCoreDateManager.h"
#import "WWeb.h"
@interface LCInfoWebVC ()
@property(nonatomic, retain) UIWebView *webView;

@property(nonatomic, retain) UIView *navigationView;            // 假导航

@property(nonatomic, retain) UIActivityIndicatorView *activity;
@property(nonatomic, retain) UIButton *backButton;              // 假返回
@property(nonatomic, retain) UIButton *collectButton;           // 收藏按钮
@property(nonatomic, retain) UIButton *shareButton;

@property(nonatomic, assign) BOOL isRight;
@property (nonatomic, strong) NSArray *arr;

@property (nonatomic, strong) LCCoreDateManager *manager;

@end

@implementation LCInfoWebVC



#pragma mark 视图已经出现了 只执行一次
- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self =  [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.arr = [NSArray array];
    }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];
     NSLog(@"%@",[self.manager applicationDocumentsDirectory]);
    // Do any additional setup after loading the view.
    self.manager = [LCCoreDateManager defaults];
    
    
    // 创建查找请求,相当于数据库查询语句
    NSFetchRequest *requestTwo = [[NSFetchRequest alloc] initWithEntityName:@"WWeb"];
    
    // 添加一个约束 谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@" , @"title", @"%@"],self.title];
    requestTwo.predicate = predicate;
    
    //通过某个 key 给数组排序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
    [requestTwo setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error;
    
    self.arr = [self.manager.managedObjectContext executeFetchRequest:requestTwo error:&error];
    NSLog(@"%ld",self.arr.count);

   
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 设置webView
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT + 145)];
    NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:self.dataUrl]];
    [self.view addSubview: self.webView];
    self.webView.scrollView.bounces = NO;
    
    // 加载请求
    [self.webView loadRequest:request];
    
    
    // 假导航条
    self.navigationView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 65)];
    self.navigationView.backgroundColor = [UIColor colorWithRed:102 / 255.0 green:163 / 255.0 blue:207 / 255.0 alpha:1];
    [self.webView addSubview:self.navigationView];
    
    
    // 返回button
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backButton setImage:[UIImage imageNamed:@"return.png"] forState:UIControlStateNormal];
    self.backButton.frame = CGRectMake(WIDTH / 25, self.navigationView.frame.size.height / 3.2, WIDTH / 9.375, HEIGHT / 16.675);
    [self.navigationView addSubview:self.backButton];
    [self.backButton addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
    
    
    // 分享按钮
    self.shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.shareButton setImage:[UIImage imageNamed:@"share.png"] forState:UIControlStateNormal];
    self.shareButton.frame = CGRectMake(WIDTH / 1.388888888888, self.navigationView.frame.size.height / 3.2, WIDTH / 9.375, HEIGHT / 16.675);
    [self.navigationView addSubview:_shareButton];
    [self.shareButton addTarget:self action:@selector(shareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    // 收藏按钮
    self.collectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.collectButton.titleLabel.font = [UIFont systemFontOfSize:10];
    self.collectButton.frame = CGRectMake(WIDTH / 1.171875, self.navigationView.frame.size.height / 3.2, WIDTH / 9.375, HEIGHT / 16.675);
    [self.collectButton addTarget:self action:@selector(saveAction:) forControlEvents:UIControlEventTouchUpInside];
    if (self.arr.count == 0) {
        [self.collectButton setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang"] forState:UIControlStateNormal];
    } else {
        [self.collectButton setBackgroundImage:[UIImage imageNamed:@"iconfont-yishoucang"] forState:UIControlStateNormal];
    }
    [self.navigationView addSubview:_collectButton];
    
}

#pragma mark - 分享按钮
- (void)shareButtonAction:(UIButton *)button{
}



#pragma mark - 收藏按钮点击方法
- (void)saveAction:(UIButton *)button{
    self.manager = [LCCoreDateManager defaults];
    
    
    // 创建查找请求,相当于数据库查询语句
    NSFetchRequest *requestTwo = [[NSFetchRequest alloc] initWithEntityName:@"WWeb"];
    
    // 添加一个约束 谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@" , @"title", @"%@"],self.title];
    requestTwo.predicate = predicate;
    
    //通过某个 key 给数组排序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
    [requestTwo setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error;
    
    self.arr = [self.manager.managedObjectContext executeFetchRequest:requestTwo error:&error];
    NSLog(@"%ld",self.arr.count);
    
    NSLog(@"%@",[self.manager applicationDocumentsDirectory]);
    

    if (self.arr.count > 0) {
        
        // 创建actionSheet】
        //1.创建UIAlertControllerStyleActionSheet类型的actionsheet
        UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"提示" message:@"取消收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *defAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            NSLog(@"确定");
        }];
        // 3.给alert添加方法
        [actionSheet addAction:defAction];
        //4.显示
        [self presentViewController:actionSheet animated:YES completion:^{
        }];
        
        
        [button setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang"] forState:UIControlStateNormal];
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"WWeb"];
        
        NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"title", @"%@"],self.title];
        request.predicate = predicate;
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
        [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        
        NSError *error;
        NSArray *array = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
        
        for (WWeb *wweb in array) {
            [self.manager.managedObjectContext deleteObject:wweb];
        }
        [self.manager saveContext];
        
    } else {
        // 创建actionSheet】
        //1.创建UIAlertControllerStyleActionSheet类型的actionsheet
        UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *defAction = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            NSLog(@"确定");
        }];
        // 3.给alert添加方法
        [actionSheet addAction:defAction];
        //4.显示
        [self presentViewController:actionSheet animated:YES completion:^{
        }];
        
        [button setBackgroundImage:[UIImage imageNamed:@"iconfont-yishoucang"] forState:UIControlStateNormal];
        // 实体类描述
        // 参数1.实体类描述  2.数据管理
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"WWeb" inManagedObjectContext:self.manager.managedObjectContext];
        
        // 创建实体
        WWeb *web = [[WWeb alloc] initWithEntity:entity insertIntoManagedObjectContext:self.manager.managedObjectContext];
        web.title = self.title;
        web.dataUrl = self.dataUrl;
        [self.manager saveContext];
        NSLog(@"999%@",[self.manager applicationDocumentsDirectory]);
    }
    
}

// 不加会直接跳入APP
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *requestedURL = [[request URL] absoluteString];
    if([requestedURL  rangeOfString:@"itunes.apple.com"].location==0) {
        return NO;
    }
    return YES;
}


#pragma mark 返回按钮点击方法
- (void)click:(UIButton *)button{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
